package com.chookss.home.running;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//新建活动列表
public class RunningAddActivity2 extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.edDescribe)
    EditText edDescribe;
    @BindView(R.id.ivBg)
    ImageView ivBg;
    @BindView(R.id.llPic)
    LinearLayout llPic;
    @BindView(R.id.llMore)
    LinearLayout llMore;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private MyContactEntityAdapter adapter;
    private List<ContactEntity> contactAllList = new ArrayList<>(); //用来存放所有数据
    private List<ContactEntity> contactLittleList = new ArrayList<>(); //人数不够《=15
    private String imgUrl = "";
    private static int SOURSE = 10;//选员工所用标识
    private boolean isEdit = false;//是否要编辑
    private  String adminCode="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_add);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("创建活动");
        addBaseData();
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(gridLayoutManager1);
        adapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, contactLittleList);
        recyclerView.setAdapter(adapter);
        recyclerView.getItemAnimator().setAddDuration(0);
        recyclerView.getItemAnimator().setChangeDuration(0);
        recyclerView.getItemAnimator().setMoveDuration(0);
        recyclerView.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        adminCode=new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
    }

    private void addBaseData() {
        ContactEntity contactEntity = new ContactEntity();
        contactEntity.setType("1");
        contactEntity.setHeadPhotoThumbUrl(new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, ""));
        contactEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        contactEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        contactEntity.setPost(new ShareUtils().getString(this, StaticClass.POST, ""));
        if (contactAllList.size() == 0) {
            //第一次
            contactLittleList.add(contactEntity);
            contactAllList.add(contactEntity);
        }else{
            contactLittleList.add(0,contactEntity);
            contactAllList.add(0,contactEntity);
        }
        ContactEntity contactEntity2 = new ContactEntity();
        contactEntity2.setType("2");
        contactEntity2.setEmployeeName("2");
        contactEntity2.setEmployeeCode("2");
        contactLittleList.add(contactEntity2);
        ContactEntity contactEntity3 = new ContactEntity();
        contactEntity3.setType("3");
        contactEntity3.setEmployeeName("3");
        contactEntity3.setEmployeeCode("3");
        contactLittleList.add(contactEntity3);
    }

    private void uploadData() {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("activityName", edTitle.getText().toString());
        map.put("imageUrl", imgUrl);
        map.put("remark", edDescribe.getText().toString());
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < contactAllList.size(); i++) {
            Map<String, String> maps = new HashMap<>();
            maps.put("employeeCode", contactAllList.get(i).getEmployeeCode());
            if (adminCode.equals(contactAllList.get(i).getEmployeeCode())) {
                maps.put("adminCd", "1");
            } else {
                maps.put("adminCd", "0");
            }
            list.add(maps);
        }
        map.put("emps", XJson.listToJsArrays(list));
        MyHttpRequest.postRequestJson(Urls.insertMoveInfo, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("活动创建成功");
                        EventBus.getDefault().post(new MyEvent("RunningAddActivity_Publish"));
                        finish();
                    } else {

                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void uploadPic() {
        showLoading();
        MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "4", new File(imgUrl), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                JSONObject result = null;
                JSONObject data = null;
                try {
                    result = new JSONObject(response.body().toString());
                    if (result.getString("code").equals("200")) {
                        data = result.getJSONObject("data");
                        imgUrl = data.getString("originalUrl");
                        uploadData();
                    } else {
                        dismissLoading();
                        if (result.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                        } else {
                            MyToast.show("封面上传失败，请稍后重试");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("封面上传失败，请稍后重试");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                MyToast.show("图片上传失败，请稍后重试");
            }
        });

    }

    class MyContactEntityAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity item) {

            RelativeLayout rlInit = helper.getView(R.id.rlInit);
            RelativeLayout rlRl = helper.getView(R.id.rlRl);
            LinearLayout llType = helper.getView(R.id.llType);
            TextView tvName = helper.getView(R.id.tvName);
            ImageView ivRunning = helper.getView(R.id.ivRunning);
            ImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivType = helper.getView(R.id.ivType);
            llType.setVisibility(View.GONE);
            rlInit.setVisibility(View.GONE);
            if ("2".equals(item.getEmployeeCode())) {
                //+
                ivRunning.setVisibility(View.VISIBLE);
                ivRunning.setBackgroundResource(R.drawable.add_icon);
                rlRl.setVisibility(View.GONE);
                tvName.setVisibility(View.INVISIBLE);
                ivType.setVisibility(View.GONE);
            } else if ("3".equals(item.getEmployeeCode())) {
                //-
                ivRunning.setVisibility(View.VISIBLE);
                ivRunning.setBackgroundResource(R.drawable.jian_icon);
                rlRl.setVisibility(View.GONE);
                tvName.setVisibility(View.INVISIBLE);
                ivType.setVisibility(View.GONE);
            } else {
                //普通人
                ivRunning.setVisibility(View.GONE);
                rlRl.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(RunningAddActivity2.this, item.getHeadPhotoThumbUrl(), ivHead, R.drawable.default_user_head, 8);
                tvName.setText(item.getEmployeeName());
                tvName.setVisibility(View.VISIBLE);
                if (isEdit) {
                    if(helper.getItemPosition()==0){
                        ivType.setVisibility(View.GONE);
                    }else{
                        ivType.setVisibility(View.VISIBLE);
                    }
                } else {
                    ivType.setVisibility(View.GONE);
                }
            }
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isNull(item.getEmployeeCode())) {
                        return;
                    }
                    Intent intent = new Intent(RunningAddActivity2.this, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", item.getEmployeeCode());
                    startActivity(intent);
                }
            });
            ivType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    contactLittleList.remove(helper.getItemPosition());
                    contactAllList.remove(helper.getItemPosition());
                    adapter.notifyItemRemoved(helper.getItemPosition());
                    adapter.notifyItemRangeChanged(helper.getItemPosition(), contactLittleList.size() - helper.getItemPosition());
                }
            });
            ivRunning.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getType().equals("2")) {
//                    //默认0是编辑 1创建分组2预览分组
                        MyApp.contactEntityLogList.clear();
                        if(contactAllList.size()>1){
                            MyApp.contactEntityLogList.addAll(contactAllList.subList(1,contactAllList.size()));
                        }
                        Intent intent = new Intent(RunningAddActivity2.this, ContactsLogChoiceActivity.class);
                        intent.putExtra("source", SOURSE + "");
                        intent.putExtra("oldContactNum", contactAllList.size()-1);
                        intent.putExtra("hrName", "已选择活动成员：");
                        startActivity(intent);
                    } else {
                        isEdit = true;
                        adapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    private void requestSTORAGECamer() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {

                            PictureSelector.create(RunningAddActivity2.this)
                                    .openGallery(SelectMimeType.ofImage())
                                    .isDisplayCamera(true)//是否显示相机入口
                                    .setMaxSelectNum(1)
                                    .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                    .isPreviewImage(true)//是否支持预览图片
                                    .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                    .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                    .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.javaa
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        } else {
                            PermissionUtils.errorPermission(RunningAddActivity2.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(RunningAddActivity2.this, denied, quick);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_" + SOURSE)) {
                if (MyApp.contactEntityLogList.size() > 0) {
                    contactAllList.clear();
                    List<String> orgCodeList = new ArrayList<>();
                    List<String> employeeCodeList = new ArrayList<>();
                    for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                        ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                        if (!contactEntity.isHalfSelect()) {
                            if (contactEntity.getType().equals("0")) {
                                orgCodeList.add(contactEntity.getEmployeeCode());
                            } else {
                                employeeCodeList.add(contactEntity.getEmployeeCode());
                            }
                        }
                    }
                    if (orgCodeList.size() > 0) {
                        getServerData(orgCodeList, employeeCodeList);
                    } else {
                        //没有组织，
                        List<ContactEntity> acceptList = new ArrayList<>();
                        for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                            ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                            contactEntity.setType("1");
                            if (!contactEntity.isHalfSelect()&&!contactEntity.getEmployeeCode().equals(adminCode)) {
                                acceptList.add(contactEntity);
                            }
                        }
                        contactAllList.addAll(acceptList);
                        setServerData();
                    }

                }
            }
        }
    }

    private void getServerData(List<String> orgCodeList, List<String> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", JSON.toJSONString(orgCodeList));
        map.put("employeeCode", JSON.toJSONString(employeeCodeList));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.getSelectedEmployee, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactEntity> serverList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            ContactEntity contactEntity = new ContactEntity();
                            contactEntity.setEmployeeName(jsonObject2.getString("employeeName"));
                            contactEntity.setEmployeeCode(jsonObject2.getString("employeeCode"));
                            contactEntity.setHeadPhotoThumbUrl(jsonObject2.getString("headPhotoThumbUrl"));
                            contactEntity.setType("1");
                            contactEntity.setEmpNum("0");
                            contactEntity.setReviewerFlag("0");
                            contactEntity.setHalfSelect(false);
                            contactEntity.setSelect(false);
                            if(!jsonObject2.getString("employeeCode").equals(adminCode)){
                                serverList.add(contactEntity);
                            }
                        }
                        contactAllList.addAll(serverList);
                        setServerData();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void setServerData() {
        if (recyclerView == null) {
            return;
        }
        contactLittleList.clear();
        if (contactAllList.size() > 15) {
            contactLittleList.addAll(contactAllList.subList(0, 13));
            llMore.setVisibility(View.VISIBLE);
        } else {
            contactLittleList.addAll(contactAllList);
            llMore.setVisibility(View.GONE);
        }
        addBaseData();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                //去除+号
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgUrl = url;
                }
                llPic.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(RunningAddActivity2.this, imgUrl, ivBg, 8);
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.llMore, R.id.llChoicePic, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llChoicePic:
                requestSTORAGECamer();
                break;
            case R.id.llMore:
                contactLittleList.addAll(13, contactAllList.subList(13, contactAllList.size()));
                adapter.notifyItemRangeChanged(13, contactAllList.size() - 13 + 2);
                llMore.setVisibility(View.GONE);
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (edTitle == null) {
                    return;
                }
                if (Utils.isNull(edTitle.getText().toString())) {
                    MyToast.show("请输入标题");
                    return;
                }
                if (Utils.isNull(edDescribe.getText().toString())) {
                    MyToast.show("请输入活动描述");
                    return;
                }
                if (Utils.isNull(imgUrl)) {
                    MyToast.show("请选择活动封面");
                    return;
                }
                if (contactLittleList.size() == 0) {
                    MyToast.show("请添加活动成员");
                    return;
                }
                uploadPic();
                break;
        }
    }
}
